package com.security.antitheft.module;


import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;

import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.hardware.Camera;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class CameraHolder {

	//Camera variables
	//a surface holder
	private SurfaceHolder sHolder; 
	//a variable to control the camera
	private Camera mCamera;
	//the camera parameters
	//	private Parameters parameters;

	private Context context;

	private String filepath;

	public CameraHolder(Context context) {

		this.context = context;
	}

	@SuppressWarnings("deprecation")
	public void takePicture() {

		try {
			mCamera = Camera.open();
			SurfaceView sv = new SurfaceView(context);

			mCamera.setPreviewDisplay(sv.getHolder());
			//set camera parameters
			mCamera.startPreview();
			mCamera.takePicture(null, null, mCall);

			//Get a surface
			sHolder = sv.getHolder();
			//tells Android that this surface will have its data constantly replaced
			sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

		} catch (Exception e) {
		}
	}

	private Camera.PictureCallback mCall = new Camera.PictureCallback() {

		public void onPictureTaken(byte[] data, Camera camera) {
			//decode the data obtained by the camera into a Bitmap
			try{
				FileOutputStream outStream = null;
				filepath = getFilePath();
				outStream = new FileOutputStream(filepath);
				outStream.write(data);
				outStream.close();
				//save to queue
				QueueHelper queue = new QueueHelper(context, true);
				queue.addPrivatePics(filepath);
				queue.close();
				queue = null;

				if (camera != null){
					camera.stopPreview();
					camera.release();
					camera = null;
				}

			} catch (Exception e){
			}

			try {

			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	};
	public String getFilePath() {

		try {
			File file;
			file = new File(context.getPackageManager().getPackageInfo(context.getPackageName(), 0).applicationInfo.dataDir, new Date().getTime()+".jpg");
			return file.getAbsolutePath();
		} catch (NameNotFoundException e) {
		}
		return null;
	}

	public void stopCamera() {
		try {
			if (mCamera != null){
				mCamera.stopPreview();
				mCamera.release();
				mCamera = null;
			}
		} catch (Exception e) {

		}
	}
}
